<template>
	<eui-page-frame topHeight="230" :withOutBorder="true">
		<template #top>
			<view class="content-img">
				<eui-nav-bar ref="BcmNavBar" title="订单评价" :storeName="sUserStoreName" :storeId="sUserStore"
					@onClickStore="clickStore" color="#333" backgroundColor="white" rightIcon="">
				</eui-nav-bar>
				<view style="background-color: #fff;height: 88rpx;" class="flex just-between align-center">
					<view style="flex:3;" class="flex align-center">
						<eui-datetime-picker type="daterange" placeholder="选择日期" :border="false"
							style="background-color: transparent;font-size: 21rpx;" @change="changeDate"
							v-model="commentDate" :clearIcon="true" />
						<eui-uicons type="clear" size="30" v-if="!!commentDate && commentDate?.length > 0"
							class="m-card-arrow m-card-arrowright" @click="clear" />
						<eui-uicons type="down" size="20" class="m-card-arrow m-card-arrowright" v-else />
					</view>
					<view style="flex:2;">
						<eui-dropdownsearch v-model:menuList="dropDownData" :themeColor="themeColor" :duration="300"
							:isCeiling="true" @onConfirm="onConfirm" style="height:88rpx">
						</eui-dropdownsearch>
					</view>
				</view>
			</view>
		</template>
		<eui-page-content>
			<eui-virtual-list @onRefresh="listPullDown" @lower="listPullUp" refresher="true" isBottom="true"
				:origList="orderList" type="list" :showHeard="false">
				<template v-slot:list="scope">
					<order-item :scope="scope" :chnlTypeList="chnlTypeList"
						@inputChange="handleInputChange"></order-item>
				</template>
				<template v-slot:bottom="scope">
					<view v-if="scope.commentId" class="flex align-center">
						<eui-button :modelValue="scope" title="取消" type="max2" single-tag="cancle"
							@buttonClick="buttonClick" style="margin-right: 20rpx;"
							v-if="scope?.showReply"></eui-button>
						<eui-button :modelValue="scope" title="更新评价" type="max2" single-tag="update"
							@buttonClick="buttonClick" style="margin-right: 20rpx;"
							v-if="!scope?.showReply"></eui-button>
						<eui-button :modelValue="scope" title="选择模板" type="max2" single-tag="chooseTem"
							@buttonClick="buttonClick" style="margin-right: 20rpx;"
							v-if="scope?.showReply"></eui-button>
						<eui-button :modelValue="scope" title="提交" type="max" single-tag="sure"
							@buttonClick="buttonClick" style="margin-right: 20" v-if="scope?.showReply"
							:disabled="scope.replyValue.length < 5"></eui-button>
						<eui-button :modelValue="scope" title="回复" type="max" single-tag="submit"
							@buttonClick="buttonClick" style="margin-right: 20rpx;"
							v-if="scope.isCanReply == '1' && ((!scope?.replyDeadlineTime) || greaterThanCurTime(new Date(scope.replyDeadlineTime.replace(/-/g, '/')))) && !scope.showReply"></eui-button>
					</view>
				</template>
			</eui-virtual-list>
		</eui-page-content>
	</eui-page-frame>
	<eui-popup ref="commentReplyTemPop" background-color="#fff" type="bottom" :mask-click="false">
		<view class="popup-content">
			<view class="popup-title flex just-between">
				<view style="font-weight: bold;">
					选择回复模版
				</view>
				<bcm-close-btn @click="close"></bcm-close-btn>
			</view>
		</view>
		<scroll-view scroll-y="true"
			style="padding: 18rpx 25rpx 8rpx 30rpx;box-sizing: border-box;height: 70vh;background-color: #fff;"
			class="text-left" @refresherrefresh="templateUpper" @scrolltolower="templateLower" refresher-enabled='true'
			:refresher-triggered="triggered">
			<radio-group @change="radioChange">
				<label class="flex" v-for="(item, index) in templateList" :key="index"
					style="line-height: 40rpx;margin-bottom: 15rpx;align-items: baseline;">
					<radio :value="item.templateId"
						v-bind:checked="currentTemplate == item.templateId ? true : false" />
					<view class="flex" style="align-items: baseline;flex: 1;">
						<view
							style="width: 40rpx;height: 40rpx;text-align: center;line-height: 40rpx;background-color: #D8D8D8;color: #fff;border-radius: 40rpx;font-size: 28rpx;margin-right: 15rpx;">
							{{ index + 1 }}
						</view>
						<view style="flex: 1;">{{ item.templateContent }}</view>
					</view>
				</label>
			</radio-group>
		</scroll-view>
		<view class="bottom-1">
			<eui-button type="max" title="确认" style="width: 50%;" singleTag="select" :modelValue="currentItem"
				@buttonClick="buttonClick" :disabled="!currentTemplate" />
		</view>
	</eui-popup>
</template>
<script setup lang="js">
import { ref, reactive, onMounted } from 'vue';
import service from '@/common/service';
import { getBcmUrl, bcmRequest } from '../../../hooks/bcmServices';
import { getBcmDictList, getBcmDictItem } from '../../../hooks/bcmUseUntils';
import { greaterThanCurTime } from '../../../hooks/useDatetimeUtil'
import { onLoad, onShow } from "@dcloudio/uni-app";
import { useMainStore } from "@/store/modules/store";
import { init } from '../../../hooks/bcmInit';
import Enjoy from "../../../common/enjoy"
import OrderItem from './component/Item.vue'
import BcmEventType from "../common/BcmEventType";
import BcmCloseBtn from '../components/BcmCloseBtn.vue'
import { storeToRefs } from 'pinia';
import { useThemeStore } from '@/store/themeStore';
import dateRangUtil from "@/common/dateRangUtil";

const themeStore = useThemeStore(); // 主题
const { theme } = storeToRefs(themeStore);
const themeColor = ref(theme._object.theme == 'theme-blue' ? '#7BDAF2' : '#FF6430')

const mainStore = useMainStore();
const { loginInfo } = mainStore;
const bcmUrl = getBcmUrl()

const BcmNavBar = ref(null);
const sUserStore = ref('');
const sUserStoreName = ref('');
const sUser = ref('');
const commentReplyTemPop = ref(null)
const currentItem = ref(null)

const CurrentPage = ref(1); //第几页
const PageSize = ref(10); //每页10条
const RowsCount = ref(0); //总条数
const PageCount = ref(1); //总页数
const orderList = ref([]);

const temCurrentPage = ref(1)
const temPageSize = ref(10); //每页10条
const temRowsCount = ref(0); //总条数
const temPageCount = ref(1); //总页数
const templateList = ref([])
const currentTemplate = ref(null)
const triggered = ref(false)

const dropDownData = ref([{
	title: '筛选(' + RowsCount.value + ')条评论',
	type: 'filter',
	children: [{
		title: "渠道",
		type: 'radio',
		dataIndex: 'chnlType',
		value: null,
		options: [{
			label: "全部",
			value: null
		}]
	}, {
		title: "回复状态",
		type: 'radio',
		dataIndex: 'replyStatus',
		value: '0',
		options: [{
			label: "全部",
			value: null
		}]
	}, {
		title: "评分",
		dataIndex: 'scoreLevel',
		type: 'checkbox',
		value: ['2', '3'],
		options: [{
			label: '好评',
			value: '1'
		}, {
			label: '中评',
			value: '2'
		}, {
			label: '差评',
			value: '3'
		}]
	}, {
		title: "评价内容",
		dataIndex: 'isHasContent',
		type: 'radio',
		value: null,
		options: [{
			label: "全部",
			value: null
		}, {
			label: "有内容",
			value: '1'
		}, {
			label: "无内容",
			value: '0'
		}]
	}]
}])
const searchValue = ref({
	replyStatus: '0',
	scoreLevel: '2,3'
});
const chnlTypeList = ref([])

const commentDate = ref([])

const changeDate = (e) => {
	commentDate.value = e;
	fetchOrderData()
}

const clear = () => {
	commentDate.value = null;
	fetchOrderData()
}

const radioChange = function (evt) {
	currentTemplate.value = evt.detail.value
}

const close = () => {
	commentReplyTemPop.value.close()
	currentItem.value = null;
	currentTemplate.value = null;
}

const getDropdownData = async () => {
	dropDownData.value[0].children[0].options = dropDownData.value[0].children[0].options.concat(chnlTypeList.value);
	dropDownData.value[0].children[1].options = dropDownData.value[0].children[1].options.concat(getBcmDictList('replyStatus'))
}

const onConfirm = (data) => {
	let params = {};
	dropDownData.value[0].children?.map(v => {
		params[v.dataIndex] = v.value
	})
	params.scoreLevel = params.scoreLevel.join(',')
	if (params.scoreLevel.indexOf('1') != -1 && params.scoreLevel.indexOf('2') != -1 && params.scoreLevel.indexOf('3') != -1) {
		params.scoreLevel = null
	}
	searchValue.value = params
	fetchOrderData()
};

const getChnlType = async function () {
	let chnlList = [];
	const response = await bcmRequest(bcmUrl.managerApi, '渠道列表', 'SearchDistinctChannelWithType', {});
	await Promise.all(response.map(v => {
		if (getBcmDictItem('chnlType', v.chnlType)) {
			chnlList.push(getBcmDictItem('chnlType', v.chnlType))
		}
	}))
	chnlTypeList.value = chnlList;
}

const setDefault = async () => {
	sUserStore.value = loginInfo?.sDefaultStore ? loginInfo.sDefaultStore : loginInfo.sUserStore;
	sUserStoreName.value = loginInfo?.sDefaultStoreName ? loginInfo.sDefaultStoreName : loginInfo.sUserStoreName;
	sUser.value = loginInfo.sUser;
}

// 选择框点击事件
const clickStore = () => {
	let parms = Enjoy.GetDialogParms();
	parms.CallBack = SelectionChanged;
	parms.SelectionType = "机构选择";
	parms.SelectedItems = sUserStore.value;
	Enjoy.OpenDialog(parms)
}

const SelectionChanged = (event) => {
	if (event.SelectionType == '机构选择') {
		// 更新机构信息
		sUserStoreName.value = event.BackParms.Value;
		sUserStore.value = event.BackParms.Key;
		mainStore.switchStore(event.BackParms.Type, sUserStore.value, sUserStoreName.value);
		uni.$emit(BcmEventType.SWITCH_STORE, { msg: '切换门店' })
		// 按新条件获取数据
		fetchOrderData();
	}
}
// 列表下拉刷新
const listPullDown = (e) => {
	fetchOrderData();
}
// 列表上拉加载
const listPullUp = (e) => {
	if (CurrentPage.value < PageCount.value) {
		CurrentPage.value = CurrentPage.value + 1;
		fetchOrderData(true);
	}
}

const maxNumber = (chnlType) => {
	let max
	switch (chnlType) {
		case 'eleme':
			max = 150;
			break;
		case 'meituan':
			max = 1024;
			break;
		default:
			max = 200;
			break;
	}
	return max
}

const handleInputChange = ({ commentId, content }) => {
	let index = orderList.value.findIndex(v => v.commentId == commentId);
	const max = maxNumber(orderList.value[index].chnlType);
	orderList.value[index].replyValue = content.substring(0, max);
}

const buttonClick = (e) => {
	let { singleTag, modelValue } = e;
	let index = orderList.value.findIndex(v => v.commentId == modelValue?.commentId);
	switch (singleTag) {
		case 'update':
			handleLoadComment(modelValue?.commentId)
			break;
		case 'submit':
			orderList.value[index].showReply = true;
			orderList.value[index].replyValue = '';
			break;
		case 'sure':
			if (orderList.value[index].replyValue?.length < 5) {
				uni.showToast({
					icon: 'none',
					title: `最少回复5个字`,
				})
				return
			}
			handleReply(orderList.value[index].replyValue, modelValue?.commentId)
			break;
		case 'cancle':
			orderList.value[index].showReply = false;
			orderList.value[index].replyValue = '';
			break;
		case 'chooseTem':
			commentReplyTemPop.value?.open('bottom');
			temCurrentPage.value = 1;
			currentItem.value = modelValue;
			console.log(modelValue,'modelValue')
			break;
		case 'select':
			let temIndex = templateList.value.findIndex(f => f.templateId == currentTemplate.value);
			console.log(temIndex,'temIndex')
			handleInputChange({ commentId: currentItem.value.commentId, content: templateList.value[temIndex].templateContent })
			close()
			break;
	}
}

const handleReply = async (tenantReplyContent, commentId) => {
	var regu = "^[ ]+$";
	var re = new RegExp(regu);
	if (!re.test(tenantReplyContent)) {
		const p = { tenantReplyContent, commentId };
		service.enjoyShowLoading('正在处理...');
		const ret = await bcmRequest(bcmUrl.managerApi, '客户评价', 'ReplyComment', p);
		service.enjoyHideLoading()
		uni.showToast({
			icon: 'none',
			title: `回复成功～`,
		})
		orderList.value = []
		fetchOrderData()
	}
}

const handleLoadComment = async (BillId) => {
	service.enjoyShowLoading('正在处理...');
	const ret = await bcmRequest(bcmUrl.managerApi, '客户评价', 'LoadComment', { BillId });
	service.enjoyHideLoading()
	uni.showToast({
		icon: 'none',
		title: `更新成功～`,
	})
	orderList.value = []
	fetchOrderData()
}

const searchConfirm = (e) => {
	searchValue.value = e.value;
	CurrentPage.value = 1;
	fetchOrderData()
}

const clearSearch = () => {
	searchValue.value = '';
	CurrentPage.value = 1;
	fetchOrderData()
}

const initDropDownParams = (params) => {
	let object = searchValue.value;
	for (var keys in object) {
		if (keys) {
			let c_oper = keys == 'scoreLevel' ? '包含' : '等于'
			params.WhereList.push({ c_col: keys, c_oper: c_oper, c_value: object[keys], c_logic: "而且" })
		}
	}
	return params
}

const fetchOrderData = async (e = undefined) => {
	service.enjoyShowLoading('正在加载...');
	if (!e) {
		CurrentPage.value = 1;
	}
	let param = {
		IsNotPage: false,
		CurrentPage: CurrentPage.value,
		PageSize: PageSize.value,
		WhereList: [
			{ c_col: "storeCode", c_oper: "等于", c_value: sUserStore.value, c_logic: "而且" }
		]
	}
	if (!!searchValue?.value) {
		initDropDownParams(param)
	}
	if (commentDate.value?.length) {
		param.WhereList.push({
			c_col: "commentTime",
			c_oper: "大于等于",
			c_value: commentDate.value[0],
			c_col_dtype: "System.DateTime",
			c_logic: "而且"
		}, {
			c_col: "commentTime",
			c_oper: "小于等于",
			c_value: commentDate.value[1],
			c_col_dtype: "System.DateTime",
			c_logic: "而且"
		})
	}
	const response = await bcmRequest(bcmUrl.managerApi, '客户评价', 'EnjoyQueryList', param);
	service.enjoyHideLoading();
	CurrentPage.value = response.CurrentPage; //第几页
	PageSize.value = response.PageSize; //每页10条
	RowsCount.value = response.RowsCount; //总条数
	dropDownData.value[0].title = '筛选(' + response.RowsCount + ')条评论';
	PageCount.value = response.PageCount; //总页数
	if (response.CurrentPage == 1) {
		orderList.value = response.ReturnObject;
	} else {
		orderList.value = orderList.value.concat(response.ReturnObject);
	}
}

const getTemplateList = async () => {
	let param = {
		IsNotPage: false,
		CurrentPage: temCurrentPage.value,
		PageSize: temPageSize.value,
		WhereList: [
			{ c_col: "storeCode", c_oper: "等于", c_value: sUserStore.value, c_logic: "而且" }
		]
	}
	const response = await bcmRequest(bcmUrl.managerApi, '评价回复模板表', 'EnjoyQueryList', param);
	temCurrentPage.value = response.CurrentPage; //第几页
	temPageSize.value = response.PageSize; //每页10条
	temRowsCount.value = response.RowsCount; //总条数
	temPageCount.value = response.PageCount; //总页数
	if (response.CurrentPage == 1) {
		templateList.value = response.ReturnObject;
	} else {
		templateList.value = templateList.value.concat(response.ReturnObject);
	}
}

const templateLower = () => {
	if (temCurrentPage.value < temPageCount.value) {
		temCurrentPage.value = temCurrentPage.value + 1;
		getTemplateList();
	}
}
// 下拉刷新
const templateUpper = function () {
	if (!triggered) {
		triggered = true;
		temCurrentPage.value = 1;
		getTemplateList();
		setTimeout(() => {
			triggered = false;
		}, 600)
	}
}

onMounted(() => {
	chnlTypeList.value = getBcmDictList('chnlType')
})

onShow(async () => {
	if (sUserStore.value) {
		await fetchOrderData();
	}
})

onLoad(async () => {
	await init();
	await getChnlType()
	await getDropdownData()
	if (!loginInfo.sUserStore) {
		BcmNavBar.value.onClickStore();
		return;
	}
	setDefault();
	commentDate.value = dateRangUtil.getCurrentMonth()
	await fetchOrderData();
	getTemplateList()
})

defineExpose({
	SelectionChanged
})
</script>
<style lang="scss" scoped>
@import "../../../main.scss";
@import "../common/common.css";

::v-deep .list_cell {
  margin-right: 0;
  margin-left: 0;
}

.content {
  display: flex;
  box-sizing: border-box;
  overflow-x: hidden;
  width: 100%;
  height: 100%;
  //background-color: $uni-background;
  padding: 0;
}

.content-img {
  position: relative;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: stretch;
  flex: 1;
  box-sizing: border-box;
  background-repeat: no-repeat;
  //background: $uni-background-img;
  background-size: 100% 150px;
}

.m-card-arrow {
  color: $uni-text-color-disable !important;
}

.m-card-arrowright {
  margin-left: 10rpx;
}

.navigation {
  flex: 0 0 auto;
}

.m-list-template-list {
  .m-list-top {
    display: "block";
  }
}

.footer {
  flex: 1;
  box-sizing: border-box;
  padding: 0;
  margin: 0;
}

.bottom {
  display: flex;
  justify-content: space-between;
  flex: 0 0 auto;
  height: 70rpx;
  padding: $uni-spacing-col-sm * 2 $uni-spacing-row-sm;
  background: #fff;
}

.bottom-1 {
  display: flex;
  justify-content: center;
  flex: 0 0 auto;
  height: 70rpx;
  padding: $uni-spacing-col-sm * 2 $uni-spacing-row-sm;
  background: #fff;
  // border-top: 1rpx solid #979797;
}

.popup-content {
  z-index: 13;
  display: flex;
  flex-direction: column;
  width: 100%;
  padding: 0;
  background-color: #fff;

  .popup-title {
    display: flex;
    align-items: center;
    box-sizing: border-box;
    width: 100%;
    height: 100rpx;
    padding-right: 36rpx;
    padding-left: 30rpx;
    font-size: 33rpx;
    line-height: 100rpx;
    border-bottom: 1px solid #f1f1f1;
  }
}

.container {
  box-sizing: border-box;
  width: 100%;
  height: 80rpx;
  color: #000;
  // padding: 0 20rpx 0 0;
  font-size: 14px;
  background-color: #fff;
  border-bottom: 2rpx solid #fff;
}

.scroll-view {
  display: flex;
  justify-content: space-around;
  align-items: center;
  box-sizing: border-box;
  overflow-x: auto;
  width: 100%;
  height: 100%;
  white-space: nowrap;
}

.white-view {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: calc(100% - 20rpx);
  height: calc(100% - 20rpx);
  margin: 0 10rpx 10rpx 10rpx;
  color: $uni-text-color-hint;
  font-family: $uni-font-family;
  font-size: $uni-font-size-level3;
  font-style: normal;
  font-weight: $uni-font-weight-level1;
  line-height: 40rpx;
  background: $uni-bg-color-inverse;
  border-radius: 20rpx;
}

::v-deep .le-dropdown-content {
  left: -60vw !important;
  width: 100vw !important;
}
</style>
